<template>
  <div class="customer-tag-manager">
    <el-dialog
      v-model="dialogVisible"
      title="客户标签管理"
      width="800px"
      :before-close="handleClose"
      class="tag-manager-dialog"
    >
      <div class="tag-manager-content">
        <!-- 当前客户标签 -->
        <div class="current-tags-section">
          <h3><el-icon><Collection /></el-icon>当前客户标签</h3>
          <div class="current-tags-container">
            <el-tag
              v-for="tag in currentTags"
              :key="tag.id"
              :type="getTagType(tag.category)"
              size="default"
              closable
              @close="removeTag(tag.id!)"
              class="current-tag"
            >
              {{ tag.name }}
              <span class="tag-category">{{ tag.category }}</span>
            </el-tag>
            <el-tag v-if="currentTags.length === 0" type="info" class="empty-tag">
              暂无标签
            </el-tag>
          </div>
        </div>

        <!-- 标签分类管理 -->
        <div class="tag-categories-section">
          <h3><el-icon><Menu /></el-icon>标签分类</h3>
          
          <!-- 分类选择 -->
          <div class="category-tabs">
            <el-button
              v-for="category in tagCategories"
              :key="category"
              :type="selectedCategory === category ? 'primary' : 'default'"
              size="default"
              @click="selectCategory(category)"
              class="category-tab"
            >
              {{ category }}
            </el-button>
          </div>

          <!-- 当前分类下的标签 -->
          <div class="category-tags-container">
            <h4>{{ selectedCategory }}标签</h4>
            <div class="available-tags">
              <el-tag
                v-for="tag in availableTagsForCategory"
                :key="tag.name"
                :type="getTagType(selectedCategory)"
                size="default"
                :class="{ 
                  'available-tag': true,
                  'already-added': isTagAlreadyAdded(tag.name)
                }"
                @click="!isTagAlreadyAdded(tag.name) && addPresetTag(tag)"
              >
                {{ tag.name }}
                <el-icon v-if="isTagAlreadyAdded(tag.name)" class="added-icon"><Check /></el-icon>
              </el-tag>
            </div>
          </div>

          <!-- 自定义标签添加 -->
          <div class="custom-tag-section">
            <h4>添加自定义标签</h4>
            <div class="custom-tag-form">
              <el-input
                v-model="customTagName"
                placeholder="输入自定义标签名称"
                style="width: 200px; margin-right: 12px;"
                @keyup.enter="addCustomTag"
              />
              <el-select
                v-model="customTagCategory"
                placeholder="选择分类"
                style="width: 120px; margin-right: 12px;"
              >
                <el-option
                  v-for="category in tagCategories"
                  :key="category"
                  :label="category"
                  :value="category"
                />
                <el-option label="自定义" value="自定义" />
              </el-select>
              <el-button
                type="primary"
                :icon="Plus"
                @click="addCustomTag"
                :disabled="!customTagName.trim() || !customTagCategory"
              >
                添加
              </el-button>
            </div>
          </div>
        </div>

        <!-- 标签统计信息 -->
        <div class="tag-statistics-section">
          <h3><el-icon><DataAnalysis /></el-icon>标签统计</h3>
          <div class="statistics-cards">
            <div class="stat-card">
              <div class="stat-number">{{ currentTags.length }}</div>
              <div class="stat-label">当前标签数</div>
            </div>
            <div class="stat-card">
              <div class="stat-number">{{ systemTagsCount }}</div>
              <div class="stat-label">系统标签</div>
            </div>
            <div class="stat-card">
              <div class="stat-number">{{ customTagsCount }}</div>
              <div class="stat-label">自定义标签</div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveChanges" :loading="saving">
            保存更改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Collection, Menu, Plus, Check, DataAnalysis 
} from '@element-plus/icons-vue'
import type { CustomerTag } from '@/api/customer'
import { customerAPI } from '@/api/customer'

// Props
interface Props {
  visible: boolean
  customerId: number
  initialTags: CustomerTag[]
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'tags-updated': [tags: CustomerTag[]]
}>()

// Reactive state
const dialogVisible = ref(false)
const currentTags = ref<CustomerTag[]>([])
const selectedCategory = ref<string>('价值分类')
const customTagName = ref('')
const customTagCategory = ref('')
const saving = ref(false)

// 预设标签数据
const PRESET_TAGS = {
  '价值分类': [
    { name: 'VIP客户', description: '高价值客户，优先服务' },
    { name: '优质客户', description: '消费能力强，忠诚度高' },
    { name: '普通客户', description: '一般消费客户' },
    { name: '价格敏感客户', description: '对价格比较敏感' },
    { name: '潜在VIP', description: '有潜力成为VIP的客户' }
  ],
  '服务特点': [
    { name: '易沟通', description: '沟通顺畅，配合度高' },
    { name: '需要关怀', description: '需要更多关注和照顾' },
    { name: '决策慢', description: '决策周期较长' },
    { name: '冲动消费', description: '容易冲动下单' },
    { name: '专业要求高', description: '对服务专业度要求高' }
  ],
  '出行特点': [
    { name: '喜欢跟团', description: '偏好跟团旅游' },
    { name: '偏爱自由行', description: '喜欢自由行方式' },
    { name: '只走精品线', description: '只选择精品旅游线路' },
    { name: '价格敏感', description: '对价格比较敏感' },
    { name: '时间灵活', description: '出行时间相对灵活' }
  ],
  '健康状态': [
    { name: '身体健康', description: '身体状况良好' },
    { name: '需要照顾', description: '需要特殊照顾' },
    { name: '行动不便', description: '行动存在一定困难' },
    { name: '慢性疾病', description: '患有慢性疾病' },
    { name: '药物依赖', description: '需要定期服药' }
  ],
  '消费习惯': [
    { name: '多次消费', description: '有过多次消费记录' },
    { name: '首次消费', description: '首次消费客户' },
    { name: '犹豫不决', description: '决策时间较长' },
    { name: '果断下单', description: '决策速度快' },
    { name: '喜欢优惠', description: '对促销活动敏感' }
  ]
}

// Computed properties
const tagCategories = computed(() => Object.keys(PRESET_TAGS) as Array<keyof typeof PRESET_TAGS>)

const availableTagsForCategory = computed(() => {
  return PRESET_TAGS[selectedCategory.value as keyof typeof PRESET_TAGS] || []
})

const systemTagsCount = computed(() => {
  return currentTags.value.filter(tag => tag.isSystem).length
})

const customTagsCount = computed(() => {
  return currentTags.value.filter(tag => !tag.isSystem).length
})

// Methods
const getTagType = (category: string) => {
  const typeMap: Record<string, string> = {
    '价值分类': 'success',
    '服务特点': 'primary',
    '出行特点': 'warning',
    '健康状态': 'danger',
    '消费习惯': 'info',
    '自定义': 'default'
  }
  return typeMap[category] || 'default'
}

const selectCategory = (category: string) => {
  selectedCategory.value = category
}

const isTagAlreadyAdded = (tagName: string) => {
  return currentTags.value.some(tag => tag.name === tagName)
}

const addPresetTag = (presetTag: { name: string; description: string }) => {
  if (isTagAlreadyAdded(presetTag.name)) {
    return
  }

  const newTag: CustomerTag = {
    id: Date.now(), // 临时ID，后端会分配正式ID
    category: selectedCategory.value as CustomerTag['category'],
    name: presetTag.name,
    value: presetTag.description,
    isSystem: true,
    createdAt: new Date().toISOString()
  }

  currentTags.value.push(newTag)
  ElMessage.success(`已添加标签：${presetTag.name}`)
}

const addCustomTag = () => {
  if (!customTagName.value.trim() || !customTagCategory.value) {
    ElMessage.warning('请输入标签名称并选择分类')
    return
  }

  if (isTagAlreadyAdded(customTagName.value.trim())) {
    ElMessage.warning('该标签已存在')
    return
  }

  const newTag: CustomerTag = {
    id: Date.now(), // 临时ID，后端会分配正式ID
    category: customTagCategory.value as CustomerTag['category'],
    name: customTagName.value.trim(),
    isSystem: false,
    createdAt: new Date().toISOString()
  }

  currentTags.value.push(newTag)
  ElMessage.success(`已添加自定义标签：${customTagName.value.trim()}`)
  
  // 清空输入
  customTagName.value = ''
  customTagCategory.value = ''
}

const removeTag = async (tagId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个标签吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    currentTags.value = currentTags.value.filter(tag => tag.id !== tagId)
    ElMessage.success('标签已删除')
  } catch {
    // 用户取消删除
  }
}

const saveChanges = async () => {
  saving.value = true
  try {
    // 这里应该调用API保存标签变更
    // 为了演示，我们先模拟保存成功
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    emit('tags-updated', [...currentTags.value])
    ElMessage.success('标签更新成功')
    handleClose()
  } catch (error) {
    console.error('保存标签失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

const handleClose = () => {
  emit('update:visible', false)
  // 重置状态
  customTagName.value = ''
  customTagCategory.value = ''
  selectedCategory.value = '价值分类'
}

// Watch props
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    // 初始化当前标签
    currentTags.value = [...props.initialTags]
  }
})

watch(dialogVisible, (newVal) => {
  if (!newVal) {
    handleClose()
  }
})
</script>

<style scoped>
.customer-tag-manager {
  /* Dialog样式在全局处理 */
}

:deep(.tag-manager-dialog) {
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px 24px 16px;
    border-radius: 8px 8px 0 0;
  }
  
  .el-dialog__title {
    color: white;
    font-weight: 600;
  }
}

.tag-manager-content {
  padding: 0;
  max-height: 600px;
  overflow-y: auto;
}

.current-tags-section {
  margin-bottom: 32px;
  padding: 24px;
  background: #f8f9ff;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.current-tags-section h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
}

.current-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.current-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  font-size: 14px;
}

.tag-category {
  font-size: 12px;
  opacity: 0.7;
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 4px;
}

.empty-tag {
  color: #9ca3af;
  font-style: italic;
}

.tag-categories-section {
  margin-bottom: 32px;
}

.tag-categories-section h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 20px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
}

.category-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.category-tab {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.category-tags-container h4 {
  margin: 0 0 16px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
}

.available-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 24px;
}

.available-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  position: relative;
}

.available-tag:hover:not(.already-added) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.available-tag.already-added {
  opacity: 0.6;
  cursor: not-allowed;
  background: #f3f4f6;
  color: #6b7280;
}

.added-icon {
  font-size: 12px;
  margin-left: 4px;
  color: #10b981;
}

.custom-tag-section {
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.custom-tag-section h4 {
  margin: 0 0 16px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
}

.custom-tag-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.tag-statistics-section {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.tag-statistics-section h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 20px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-card {
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0 0 0;
  border-top: 1px solid #e5e7eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.tag-manager-dialog) {
    width: 95% !important;
    margin: 20px auto !important;
  }
  
  .statistics-cards {
    grid-template-columns: 1fr;
  }
  
  .custom-tag-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .custom-tag-form .el-input,
  .custom-tag-form .el-select {
    width: 100% !important;
  }
}
</style>